package com.example.admin.controller;

import com.example.admin.service.CategoryService;
import com.example.common.Result;
import com.example.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("")
    public Result add(@RequestBody Category category){
        if(category.getCategoryName().length()>20){
            log.info("分类{}字符个数超过20",category.getCategoryName());
            return Result.error();
        }
        if (!categoryService.add(category)){
        return Result.error();
        }
        return Result.success(categoryService.add(category));
    }

    @GetMapping("findAll")
    public Result findAll(){
        List<Category> list = categoryService.findAll();
        return Result.success(list);
    }

    @GetMapping("findById/{id}")
    public Result findById(@PathVariable String id){
        Category category = categoryService.findById(id);

        return Result.success(category);
    }
    @PutMapping("update")
    public Result update(@RequestBody Category category){
        if(category.getCategoryName().length()>20){
            log.info("分类{}字符个数超过20",category.getCategoryName());
            return Result.error();
        }
        boolean res = categoryService.update(category);
        return Result.success( res);
    }
    @DeleteMapping("{id}")
    public  Result deleteById(@PathVariable String id){
        boolean result = categoryService.deleteById(id);
        return Result.success(result);
    }

}
